from django.http import JsonResponse
from web.models import Users
from django import forms
from django.forms.models import model_to_dict
import json
from django.db.models import Q

# 统一返回格式
def result(code, message, data=None):
    return JsonResponse({'code': code, 'message': message, 'data': data})


# 用户表单
class UserForm(forms.ModelForm):
    class Meta:
        model = Users
        fields = ['username', 'password', 'email']


# 用户注册
def register(request):
    try:
        if request.method == 'POST':
            form = UserForm(request.POST)
            if form.is_valid():
                form.save()
                user = model_to_dict(form.instance)
                user.pop('password')
                return result(200, '用户注册成功', user)
            else:
                return result(400, '用户注册失败', json.loads(form.errors.as_json()))
        else:
            return result(405, '请求方法错误')
    except ValueError as e:
        print(e.args[0])
        return result(400, '用户注册失败', e.args[0])

# 用户登录
def login(request):
    try:
        if request.method == 'POST':
            # 可以通过用户名或者邮箱登录, 使用Q查询
            user_name = request.POST.get('username')
            user_email = request.POST.get('email')
            user_password = request.POST.get('password')
            # 判断是否传了参数
            if not user_name and not user_email:
                return result(400, '用户登录失败', '请传入用户名或邮箱')
            if not user_password:
                return result(400, '用户登录失败', '请传入密码')
            # 查询用户
            user = Users.objects.filter(Q(username=user_name) | Q(email=user_email), password=user_password).first()
            if user:
                user = model_to_dict(user)
                user.pop('password')


                # 设置session
                request.session['user'] = user
                # 设置session过期时间
                request.session.set_expiry(0)


                return result(200, '用户登录成功', user)
            else:
                return result(400, '用户登录失败', '用户不存在')
        else:
            return result(405, '请求方法错误')
    except ValueError as e:
        return result(400, '用户登录失败', e.args[0])
